<?php

namespace App\Http\Controllers\admin\article;

use App\Http\Controllers\Controller;
use App\Logic\Es\EsService;
use App\Models\Article;
use Elasticsearch\ClientBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use think\Exception;

class ArticleController extends Controller
{
    //
    public function healthArticle(Request $request){
        //获取用户名
        $userName=$request->get('title');
        //es搜索高亮显示
        if (!empty($userName)) {
            $host = ['127.0.0.1:9200'];
            //根据主机地址和端口号创建一个 ElasticSearch 客户端实例
            $client = ClientBuilder::create()
                ->setHosts($host)
                ->build();
            $params = [
                'index' => 'llliu',
                //设置查询条件和高亮显示条件
                'body' => [
                    //设置查询条件
                    'query' => [
                        'match' => [
                            'title' => [
                                'query'=>$userName
                            ]
                        ]
                    ],
                    // 设置高亮显示条件
                    'highlight' => [
                        'fields' => [
                            'title'=>[
                                'pre_tags' => ["<span style='background-color:pink;width: 200px;height: 30px'>"],
                                'post_tags' => ["</span>"]
                            ]
                        ]
                    ]
                ]
            ];
            //发送查询请求，并获取查询结果
            $response = $client->search($params);
            //dd($response);
            //Elasticsearch 返回的搜索结果
            //它是一个数组，包含了匹配查询条件的所有文档数据
            $data=$response['hits']['hits'];
            //dd($data);
        }else{
            //获取全部数据
            $data=Article::get();
        }
        //返回管理员列表并传值
        return view('hospital/healtharticle',['data'=>$data]);
    }

    /**
     * @后台用户管理员添加页面
     * @user 刘璇
     * @method get
     * @url https://www.house.com/user/user_create
     * @data
     * @return \Illuminate\Http\Response
     */
    public function articleCreate()
    {
        //返回添加页面 并 传值
        return view('hospital/articlecreate');
    }



    /**
     * @后台用户管理员添加方法
     * @user 刘璇
     * @method post
     * @url https://www.house.com/user/role_add
     * @data
     * @return \Illuminate\Http\Response
     */
    public function articleAdd(Request $request)
    {
        try {
            //获取除了"_token"和"s"以外的其他数据并赋值
            $data=$request->except("_token","s");
            //获取文件
            $file=$request->file('img');
            //调用EsService方法
            $res = EsService::esService($data,$file);
            //返回
            return redirect("hospital/health_article");
        }catch (Exception $exception){
            Log::info($exception->getMessage());
        }
    }




}
